"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

var _url = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/url"));

/**
 * 下载文件
 *
 * @since 1.1.0
 * @category 实用函数
 * @param {blob|file|string} flowStr 文件类型.
 * @param {object} config 配置参数.
 * @param {boolean} config.name 下载文件名称(含后缀).
 *
 * @returns {File} 文件
 *
 * @example
 *
 * // blob类型
 * const blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"})
 * z.downFile(blob, "hello world.txt")
 *
 * // file类型
 * const file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"})
 * z.downFile(file)
 *
 * // URL类型
 * z.downFile("https://httpbin.org/image", "image.jpg")
 *
 */
var isMacOSWebView = /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent);
var downFile = 'download' in HTMLAnchorElement.prototype && !isMacOSWebView ? function (blob, name, opts) {
  var a = document.createElement('a');
  name = name || blob.name || 'download';
  a.download = name;
  a.rel = 'noopener';

  if (typeof blob === 'string') {
    a.href = blob;

    if (a.origin !== location.origin) {
      corsEnabled(a.href) ? download(blob, name, opts) : click(a, a.target = '_blank');
    } else {
      click(a);
    }
  } else {
    a.href = _url.default.createObjectURL(blob);
    setTimeout(function () {
      _url.default.revokeObjectURL(a.href);
    }, 4e4); // 40s

    setTimeout(function () {
      click(a);
    }, 0);
  }
} : function (blob, name, opts, popup) {
  popup = popup || window.open('', '_blank');

  if (popup) {
    popup.document.title = popup.document.body.innerText;
    popup.document.body.innerText = 'downloading...';
  }

  if (typeof blob === 'string') return download(blob, name, opts);
  var force = blob.type === 'application/octet-stream';
  var isSafari = /constructor/i.test(HTMLElement);
  var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);

  if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== 'undefined') {
    var reader = new FileReader();

    reader.onloadend = function () {
      var url = reader.result;
      url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;');
      if (popup) popup.location.href = url;else location = url;
      popup = null;
    };

    reader.readAsDataURL(blob);
  } else {
    var url = _url.default.createObjectURL(blob);

    if (popup) popup.location = url;else location.href = url;
    popup = null;
    setTimeout(function () {
      _url.default.revokeObjectURL(url);
    }, 4e4); // 40s
  }
};

function download(url, name, opts) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = 'blob';

  xhr.onload = function () {
    downFile(xhr.response, name, opts);
  };

  xhr.onerror = function (err) {
    throw new Error(err);
  };

  xhr.send();
}

function corsEnabled(url) {
  var xhr = new XMLHttpRequest();
  xhr.open('HEAD', url, false);

  try {
    xhr.send();
  } catch (e) {}

  return xhr.status >= 200 && xhr.status <= 299;
}

function click(node) {
  try {
    node.dispatchEvent(new MouseEvent('click'));
  } catch (e) {
    var evt = document.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
    node.dispatchEvent(evt);
  }
}

module.exports = downFile;